package hot;

import java.util.*;

/**
 * @author way
 * @create 2025-03-19 19:28
 */
public class _394_decodeString {
    public String decodeString(String s) {
        LinkedList<Integer> numStack = new LinkedList<>();
        LinkedList<StringBuilder> strStack = new LinkedList<>();

        int digit = 0;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isDigit(ch)) {
                int num = ch - '0';
                digit = digit * 10 + num;
            } else if (ch >= 'a' && ch <= 'z') {
                res.append(ch);
            } else if (ch == '[') {
                numStack.push(digit);
                strStack.push(res);
                digit = 0;
                res = new StringBuilder();
            } else if (ch == ']') {
                int count = numStack.pop();
                StringBuilder backStr = strStack.pop();
                for (int j = 0; j < count; j++) {
                    backStr.append(res.toString());
                }
                res = backStr;
            }
        }

        return res.toString();
    }
}
